<template>
  <div id="app">
    <div class="container-fluid no-select" @contextmenu="contextMenu($event)" @click="clear"
         @mousemove="mmove"
         @mouseup="mup('')"
    >
      <div class="row tool-bar justify-content-between">
        <div class="col text-left">
          <input type="file" id="upload" :disabled="!url" class="file-input-hide" @change="processFile($event)" multiple
                 accept="*/*">
          <label for="upload" class="btn btn-primary" :class="{'disabled': !url}">上传</label>
          <label class="btn btn-outline-primary" @click="openCreateFolder">新建文件夹</label>
          <!--<label class="btn btn-outline-primary">删除</label>-->
          <!--<label class="btn btn-outline-primary">重命名</label>-->
          <!--<label class="btn btn-outline-primary">移动到</label>-->
          <!--<label class="btn btn-outline-primary">复制到</label>-->
        </div>
        <div class="col-1 no-select text-right">
          <div class="row align-items-center">
            <div class="list-count">共{{files.length}}个</div>
            <div class="display-mode" @click="changeDisplayType">
              <i :class="'icono-'+ displayType"></i>
            </div>
          </div>
        </div>
        <!--<div class="col-3">-->
        <!--<div class="nav-item dropdown text-left">-->
        <!--<a class="">排序</a>-->
        <!--<div class="dropdown-menu">-->
        <!--<a class="dropdown-item" href="#">Action</a>-->
        <!--<a class="dropdown-item" href="#">Another action</a>-->
        <!--<a class="dropdown-item" href="#">Something else here</a>-->
        <!--<div class="dropdown-divider"></div>-->
        <!--<a class="dropdown-item" href="#">Separated link</a>-->
        <!--</div>-->
        <!--</div>-->
        <!--<label class="btn btn-outline-primary">切换</label>-->
        <!--</div>-->
      </div>


      <div class="row justify-content-between">
        <div class="col text-left breadcrumb">

          <ul>
            <li><a href="#" class="back-prev" @click="back">返回上一层</a></li>
            <li><a href="#" class="show-all" @click="open('')">全部文件</a></li>
            <li v-for="(u,index) in getUrlList" :key="u" class="path-item">
              <span v-if="getUrlList.length - 1 === index">{{u}}</span>
              <a href="#" @click="openIndex(index)" v-if="getUrlList.length - 1 !== index">{{u}}</a>
            </li>
          </ul>
        </div>

      </div>
      <div class="row flex-wrap  justify-content-start main-content" :class="'item-' + displayType">

        <div class="card folder hover"
             @mouseover.stop="mover(file)"
             @mouseleave.stop="mleave(file)"
             @mousedown.stop="mdown($event, file)"
             @mouseup.stop="mup(file)"
             @contextmenu="openRightMenu($event, file)"
             v-for="file in files"
             v-if="file.type === 'folder'" @dblclick.stop="open(file.path)" :key="file.path"
             :title="file.name">
          <svg class="icon" aria-hidden="true">
            <use :xlink:href="'#icon-' + file.type"></use>
          </svg>
          <div class="file-name" v-text="file.name"></div>
        </div>
        <div class="card file" :class="{'hover': !fileMove.isShow}"
             @mouseover.stop="mover('')"
             @mouseleave.stop="mleave(file)"
             @mousedown.stop="mdown($event, file)"
             @mouseup.stop="mup(file)"
             @contextmenu="openRightMenu($event,file)" v-for="file in files"
             v-if="file.type !== 'folder'"
             :key="file.path"
             :title="file.name">
          <svg class="icon" aria-hidden="true">
            <use :xlink:href="'#icon-' + getFileType(file.type)"></use>
          </svg>
          <div class="file-name" v-text="file.name"></div>
        </div>
      </div>
    </div>

    <div class="contextMenu" v-show="showMenu" :style="{top:menu.top, left: menu.left}">
      <ul @click.stop="showMenu = !showMenu">
        <li v-if="menu.type === 'folder'" @click="open(selectObj.oldPath)">打开</li>
        <li v-if="menu.type === 'file'" @click="downloadFile">下载</li>
        <li @click="open(url)">刷新</li>
        <li v-if="menu.type" @click="openRenamePopup">重命名</li>
        <li v-if="menu.type" @click="removeFile(selectObj.oldPath)">删除</li>
        <li><label for="upload" :class="{'disabled': !url}">上传</label></li>
        <li @click="back">返回</li>
      </ul>
    </div>

    <div class="modal fade show rename-popup" role="dialog" v-show="renamePopup">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">重命名</h5>
            <button type="button" class="close no-select" data-dismiss="modal" aria-label="Close">
              <span @click="renamePopup = false">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <form>
              <div class="form-group text-left">
                <label for="recipient-name" class="col-form-label ">请输入名称:</label>
                <input type="text" class="form-control" autocomplete="off" v-model="selectObj.name" id="recipient-name">
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="renamePopup = false">取消
            </button>
            <button type="button" class="btn btn-primary" @click="saveRename">确定</button>
          </div>
        </div>
      </div>
    </div>

    <div class="move-shadow" v-show="fileMove.isShow"
         :style="{top:fileMove.moveTop, left: fileMove.moveLeft, 'pointer-events: none': fileMove.isThrough }">
      <svg class="icon" aria-hidden="true">
        <use :xlink:href="'#icon-' + getFileType(fileMove.source.type)"></use>
      </svg>
      <div class="move-target" v-show="!!fileMove.target.name && fileMove.target.path !== fileMove.source.path">
        <div class="target-content">
          -> 移动到 <span v-text="fileMove.target.name"></span>
        </div>
      </div>
    </div>

    <create-folder @refresh="open(url)" @close-popup="closeCreateFolder" v-bind:currentPath="url"
                   v-if="createFolderObj.isShow"></create-folder>


  </div>
</template>

<script>
  import {FileList, FileUpload, FileReName, FileMove, FileRemove} from './api/api.js'
  import './assets/js/iconfont'
  import CreateFolder from './components/CreateFolader'

  export default {
    name: 'app',
    components: {
      'create-folder': CreateFolder
    },
    data() {
      return {
        url: '',
        href: '',
        basicPath: [],
        displayType: 'tiles', // list
        files: [],
        uploadFiles: [],
        showMenu: false,
        renamePopup: false,
        fileTypes: {
          'audio': ['mp3'],
          'csv': ['csv'],
          'excel': ['xls', 'xlsx'],
          'word': ['doc', 'docx'],
          'exe': ['exe'],
          'html': ['html', 'svg'],
          'image': ['jpg', 'image', 'png', 'gif'],
          'pdf': ['pdf'],
          'ppt': ['ppt', 'pptx'],
          'psd': ['psd'],
          'rtf': ['rtf'],
          'video': ['mp4', 'avi'],
          'txt': ['txt'],
          'zip': ['zip', 'rar', '7z'],
          'xml': ['xml']
        },
        menu: {
          top: '',
          left: '',
          type: ''
        },
        selectObj: {
          oldPath: '',
          name: '',
          newPath: '',
          type: ''
        },
        fileMove: {
          isMove: false,
          isShow: false,
          isThrough: true,
          startTop: 0,
          startLeft: 0,
          moveTop: '',
          moveLeft: '',
          source: {},
          target: {}
        },
        rightObj: {
          file: {}
        },
        createFolderObj: {
          isShow: false
        }
      }
    },
    computed: {
      getUrlList: function () {
        if (!this.url) {
          return [];
        }
        return this.url.split('\\');

      }
    },
    mounted: function () {
      let _this = this;
      this.$nextTick(() => {

        let _href = window.location.href;
        let offsetPath = '';
        let segIndex = _href.indexOf('#');
        if (segIndex > -1) {
          _this.href = _href.substr(0, segIndex);
          offsetPath = _href.substr(segIndex + 1);
        } else {
          _this.href = _href;
        }
        _this._getFileList(offsetPath);
      })
    },
    methods: {
      openCreateFolder() {
        this.createFolderObj.isShow = true;
      },
      closeCreateFolder() {
        this.createFolderObj.isShow = false;
      },
      openRenamePopup() {
        this.renamePopup = true;
        let paths = this.selectObj.oldPath.split('\\');
        this.selectObj.name = paths[paths.length - 1];
      },
      openRightMenu(e, file) {
        this.rightObj.file = file;
        this.selectObj.oldPath = file.path;
        this.selectObj.type = file.type;
        this.selectObj.newPath = file.path;
        this.contextMenu(e, file.type);
      },
      getFileType: function (suffix) {
        if (!suffix) return;
        if (suffix === 'folder') {
          return suffix;
        }

        suffix = suffix.replace('.', '');
        let type = this._.findKey(this.fileTypes, function (types) {
          return types.indexOf(suffix) !== -1;
        });
        return !type ? 'unknown' : type;
      },
      openIndex(index) {
        if (this.getUrlList.length - 1 !== index) {
          let urls = this._.remove(this.getUrlList, function (url, i) {
            return i <= index;
          });
          this.open(urls.join('\\'));
        }

      },
      contextMenu(e, type) {

        //TODO 需要处理边界问题
        e.stopPropagation();
        e.preventDefault();
        if (!type) {
          type = '';
        } else if (type !== 'folder') {
          type = 'file';
        }
        this.menu.type = type;
        this.menu.top = this.getMousePosition(e).top + 'px';
        this.menu.left = this.getMousePosition(e).left + 'px';
        this.showMenu = true
      },
      _getFileList(path) {
        path = decodeURIComponent(path);
        let _this = this;
        FileList(path).then(result => {
          _this.files = result;
          _this.url = path;
          if (!_this.basicPath.length) {
            _this._(result).forEach(file => {
              if (file.type === 'folder') {
                let path = decodeURIComponent(file.path.replace('\\', ''))
                _this.basicPath.push(file.path.replace('\\', ''));
              }
            })
          }
        });
      },
      getProgress(e) {
        console.log(e)
      },
      processFile(e) {
        let files = e.target.files;
        this._(files).forEach(file => {
          this.uploadFiles.push(file)
        });
        this.upload()
      },
      open(path) {
        this.setAnchor(path);
        this._getFileList(path)
      },
      upload() {
        let _this = this;
        this.uploadFiles.forEach((file) => {
          FileUpload(file, _this.url, _this.getProgress).then(res => {
            if (res.status === 'success') {
              _this.open(_this.url);
            }
          })
        })
      },
      back() {
        let url = this.url.substring(0, this.url.lastIndexOf('\\'));
        this.url = url;
        this.open(url);
      },
      setAnchor(path) {
        if (path) {
          window.location.href = this.href + "#" + path;
        } else {
          window.location.href = this.href;
        }
      },
      clear() {
        this.showMenu = false;
        this.renamePopup = false;
        this.menu.type = '';
      },
      saveRename() {
        let _this = this;
        let newPath = this.selectObj.oldPath.split('\\');
        newPath.length -= 1;
        newPath.push(this.selectObj.name);
        this.selectObj.newPath = newPath.join('\\');
        FileReName(this.selectObj).then(result => {
          if (result && result.status === 'success') {
            _this.renamePopup = !_this.renamePopup;
            _this.open(_this.url);
          }
        });
      },
      mdown(e, file) {
        let _this = this;
        _this.fileMove.startTop = _this.getMousePosition(e).top;
        _this.fileMove.startLeft = _this.getMousePosition(e).left;
        _this.fileMove.isMove = true;
        _this.fileMove.source = file;
      },
      mmove(e) {
        let _this = this;

        if (!_this.fileMove.isMove) {
          return false;
        }
        e.stopPropagation();
        e.preventDefault();
        let _top = _this.getMousePosition(e).top;
        let _left = _this.getMousePosition(e).left;

        if (Math.abs(_this.fileMove.startTop - _top) > 10
          || Math.abs(_this.fileMove.startLeft - _left) > 10) {
          _this.fileMove.isShow = true;
          _this.fileMove.moveTop = _top + 'px';
          _this.fileMove.moveLeft = _left + 'px';
        }

      },
      mup(file) {
        let _this = this;
        if (_this.fileMove.isShow) {
          if (file.type === 'folder') {
            if (_this.fileMove.source.path !== _this.fileMove.target.path) {
              let sources = _this.fileMove.source.path.split('\\');
              let target = _this.fileMove.target.path;
              target += '\\' + sources[sources.length - 1];
              FileMove(_this.fileMove.source.path, target).then(result => {
                if (result && result.status === 'success') {
                  _this.open(_this.url);
                }
              });
            }
          }
          _this.fileMove.source = {};
        }
        _this.fileMove.isMove = false;
        _this.fileMove.startTop = 0;
        _this.fileMove.startLeft = 0;
        _this.fileMove.moveTop = '';
        _this.fileMove.moveLeft = '';
        _this.fileMove.isShow = false;
      },
      mover(file) {

        //TODO  需要判断文件


        let _this = this;
        if (!_this.fileMove.isMove) {
          return false;
        }
        if (file) {
          _this.fileMove.target = file;
        }
      },
      mleave(e) {
        let _this = this;
        if (!_this.fileMove.isMove) {
          return false;
        }
        // console.log(e)
        _this.fileMove.target = {};
        _this.fileMove.isThrough = true;
      },
      getMousePosition(e) {
        return {
          top: e.clientY + document.documentElement.scrollTop,
          left: e.clientX + document.documentElement.scrollLeft
        }
      },
      downloadFile(file) {
        let _this = this;
        let _file = {};
        if (file && file.name) {
          _file = file;
        } else if (_this.rightObj.file) {
          _file = _this.rightObj.file;
        } else {
          return false;
        }
        window.open(window.location.protocol + '//' + window.location.host + '/download?path=' + _file.path, '_blank');
      },
      removeFile(path) {
        let _this = this;
        let message = `您确认删除 ${this.selectObj.name} 文件吗?`;
        if (this.selectObj.type === 'folder') {
          message = `您确认删除 ${this.selectObj.name} 文件夹吗?`;
        }
        if (confirm(message)) {
          FileRemove(path).then((result) => {
            if (result.status === 'success') {
              _this.open(_this.url);
            }
          })
        }
      },
      changeDisplayType() {
        if (this.displayType === 'list') {
          this.displayType = 'tiles';
        } else {
          this.displayType = 'list';
        }
      }
    }
  }
</script>
